#include "common.h"

Server *g_server;

Server * Init_Server() 
{
    ds_pool_s *pool;
    Server *server;

    /* 
        Create the memory pool
        The pool size = (sizeof(CONN) * MAX_CONN + sizeof(Event) * MAX_CONN * 2 + some other small bytes...)
        */
    pool = DS_CreatePool(MAX_CONN * 100);
    if (pool == NULL) {
        Log_Write_Stderr("Create Cycle Pool Failed");
        return NULL;
    }

    server = DS_Pcalloc(pool, sizeof(Server));
    if (server == NULL) {
        Log_Write_Stderr("Alloc Server Memory Failed");
        DS_DestroyPool(pool);
        return NULL;
    }

    server->pool = pool;
    server->log = DS_Pcalloc(pool, sizeof(Log));
    if (server->log == NULL) {
        Log_Write_Stderr("Alloc Log Memory Failed");
        DS_DestroyPool(pool);
        return NULL;
    }
    if (Init_Log(server) != 0) {
        Log_Write_Stderr("Init Log Failed");
        DS_DestroyPool(pool);
        return NULL;
    }
    
    return server;
}


int main()
{
    int rc;

    /* Notice: If first Init_Signal then create daemon, there will be segment err when exit main() */
    if (Process_Daemon() != PROCESS_OK) {
        Log_Write_Stderr("Daemon Failed");
        return 0;
    }

    if (Init_Signal() != PROCESS_OK) {
        Log_Write_Stderr("Init Signal Failed");
        return 0;
    }
    
    /* Identify the process type, it helps in signal handler */
    g_Process = PROCESS_MASTER;

    g_server = Init_Server();
    if (g_server == NULL) {
        Log_Write_Stderr("Init Server Failed");
    	return 0;
    }

    g_server->serverfd = NET_TcpServer(80, "123.125.104.155");
    if (g_server->serverfd < 0) {
        Log_Write_Stderr("Create Server Socket Failed");
        goto End;
    }
    if (NET_NonBlock(g_server->serverfd) != NET_OK) {
        Log_Write_Stderr("Server Socket Nonblock Failed");
        goto End;
    }
    Process_StartMaster();

End:
    if (g_server->log->fd) {
    	close(g_server->log->fd);
    }
    if (g_server->epfd) {
    	close(g_server->epfd);
    }
    if (g_server->serverfd > 0) {
    	close(g_server->serverfd);
    }
    DS_DestroyPool(g_server->pool);
    return 1;
}

